package com.gy.controller.assistant;

import com.gy.controller.assistant.dto.ChatMessageDTO;
import com.gy.controller.assistant.dto.ConversationSummaryDTO;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.data.message.SystemMessage;
import dev.langchain4j.service.UserMessage;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class MongoChatMemoryStore implements ChatMemoryStore {

    @Autowired
    private MongoTemplate mongoTemplate;

    // 注意：此处的memoryId实际是"userId:memoryId"的组合字符串
    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        try {
            // 直接使用组合后的memoryId作为查询条件
            Criteria criteria = Criteria.where("memoryId").is(memoryId.toString());
            Query query = Query.query(criteria);
            ChatMessages chatMessages = mongoTemplate.findOne(query, ChatMessages.class);

            if (chatMessages == null || chatMessages.getContent() == null) {
                return new LinkedList<>();
            }

            return ChatMessageDeserializer.messagesFromJson(chatMessages.getContent());
        } catch (Exception e) {
            System.err.println("读取消息失败：" + e.getMessage());
            return new LinkedList<>();
        }
    }

    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> messages) {
        try {
            String globalMemoryId = memoryId.toString(); // 确保传入的是"userId:会话ID"
            String messagesJson = ChatMessageSerializer.messagesToJson(messages);
            ChatMessages chatMessages = new ChatMessages();
            chatMessages.setMemoryId(globalMemoryId); // 强制存储为"userId:会话ID"
            chatMessages.setContent(messagesJson);
            chatMessages.setLastUpdateTime(LocalDateTime.now());
            mongoTemplate.save(chatMessages);
        } catch (Exception e) {
            System.err.println("保存消息失败：" + e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public void deleteMessages(Object memoryId) {
        Criteria criteria = Criteria.where("memoryId").is(memoryId.toString());
        mongoTemplate.remove(Query.query(criteria), ChatMessages.class);
    }

    /**
     * 查询用户的所有会话（仅返回概览信息）
     */
    public List<ConversationSummaryDTO> getUserConversations(Long userId) {
        try {
            // 匹配 memoryId 以 "userId:" 开头的所有记录（用户的所有会话）
            Criteria criteria = Criteria.where("memoryId").regex("^" + userId + ":");
            Query query = Query.query(criteria).with(Sort.by(Sort.Direction.DESC, "lastUpdateTime"));

            List<ChatMessages> allConversations = mongoTemplate.find(query, ChatMessages.class);

            return allConversations.stream().map(chatMsg -> {
                ConversationSummaryDTO dto = new ConversationSummaryDTO();
                // 确保memoryId为字符串类型
                String memoryIdStr = chatMsg.getMemoryId().toString();
                // 强制按"userId:会话ID"格式拆分，最多拆分为两部分
                String[] parts = memoryIdStr.split(":", 2);

                if (parts.length > 1) {
                    // 正常格式：提取会话ID部分（如"1001:2001" -> "2001"）
                    dto.setMemoryId(parts[1]);
                } else {
                    // 异常格式：直接使用原始值并记录错误日志
                    dto.setMemoryId(memoryIdStr);
                    System.err.println("非法memoryId格式（无冒号分隔）：" + memoryIdStr + "，用户ID：" + userId);
                }

                // 提取第一条非系统消息（过滤SystemMessage后取第一条）
                List<ChatMessage> messages = ChatMessageDeserializer.messagesFromJson(chatMsg.getContent());
                List<ChatMessage> nonSystemMessages = messages.stream()
                        .filter(msg -> !(msg instanceof SystemMessage))
                        .collect(Collectors.toList());

                if (!nonSystemMessages.isEmpty()) {
                    ChatMessage firstMsg = nonSystemMessages.get(0);
                    String content = "";
                    if (firstMsg instanceof dev.langchain4j.data.message.UserMessage) {
                        dev.langchain4j.data.message.UserMessage userMessage = (dev.langchain4j.data.message.UserMessage) firstMsg;
                        if (userMessage.hasSingleText()) {
                            content = userMessage.singleText();
                        }
                    } else if (firstMsg instanceof dev.langchain4j.data.message.AiMessage) {
                        dev.langchain4j.data.message.AiMessage aiMessage = (dev.langchain4j.data.message.AiMessage) firstMsg;
                        content = aiMessage.text(); // AiMessage直接通过text()获取内容
                    }

                    dto.setFirstMessage(content.length() > 50
                            ? content.substring(0, 50) + "..."
                            : content);
                } else {
                    dto.setFirstMessage("无有效交互消息");
                }

                dto.setLastUpdateTime(chatMsg.getLastUpdateTime()); // 设置最后更新时间
                return dto;
            }).collect(Collectors.toList());
        } catch (Exception e) {
            System.err.println("查询用户会话列表失败：" + e.getMessage());
            e.printStackTrace(); // 打印异常堆栈，便于排查问题
            return new ArrayList<>();
        }
    }


    /**
     * 查询单个会话的详细聊天记录
     */
    public List<ChatMessageDTO> getConversationDetails(String globalMemoryId) {
        try {
            ChatMessages chatMessages = mongoTemplate.findOne(
                    Query.query(Criteria.where("memoryId").is(globalMemoryId)),
                    ChatMessages.class
            );

            if (chatMessages == null || chatMessages.getContent() == null) {
                return new ArrayList<>();
            }

            // 反序列化消息列表并转换为DTO
            List<ChatMessage> messages = ChatMessageDeserializer.messagesFromJson(chatMessages.getContent());
            return messages.stream().map(msg -> {
                ChatMessageDTO dto = new ChatMessageDTO();

                // 使用全限定类名判断用户消息
                dto.setRole(msg instanceof dev.langchain4j.data.message.UserMessage ? "USER" : "AI");

                // 根据消息类型提取内容
                String content = "";
                if (msg instanceof dev.langchain4j.data.message.UserMessage) {
                    dev.langchain4j.data.message.UserMessage userMsg = (dev.langchain4j.data.message.UserMessage) msg;
                    if (userMsg.hasSingleText()) {
                        content = userMsg.singleText();
                    }
                } else if (msg instanceof dev.langchain4j.data.message.AiMessage) {
                    dev.langchain4j.data.message.AiMessage aiMsg = (dev.langchain4j.data.message.AiMessage) msg;
                    content = aiMsg.text(); // 确保AiMessage有text()方法
                }
                dto.setContent(content);

                // 注意：这里的时间戳是临时值，建议在存储消息时就记录真实时间
                dto.setTimestamp(LocalDateTime.now());
                return dto;
            }).collect(Collectors.toList());
        } catch (Exception e) {
            System.err.println("查询会话详情失败：" + e.getMessage());
            return new ArrayList<>();
        }
    }

}
